package com.neuedu.corejava.ch14;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class ChatClient {

	public void chat(String host, int port) {
		Socket socket = null;
		InputStream inputStream = null;
		OutputStream outputStream = null;
		Scanner scanner = null;
		try {
			// 1.打开socket连接，连接服务器
			socket = new Socket(host, port);
			
			System.out.println("连接服务器成功");
			// 打开输出输入流
			inputStream = socket.getInputStream();
			outputStream = socket.getOutputStream();
			scanner = new Scanner(System.in);
			byte[] buffer = new byte[512];

			while (true) {
				// 3.打开键盘输入，并输入聊天内容
				System.out.println("请输入聊天内容(结束聊天发送quit)：");

				String word = scanner.nextLine();
				// 4.把聊天内容发送到服务器
				outputStream.write(word.getBytes());
				System.out.println("发送到服务器成功！");
				// 如果用户输入quit则退出聊天
				if ("quit".equalsIgnoreCase(word)) {
					break;
				}
				// 读取服务器返回的数据，并显示
				int len = inputStream.read(buffer);
				String reply = new String(buffer, 0, len).trim();
				System.out.println(reply);
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			closeAll(socket, inputStream, outputStream, scanner);
		}

	}

	private void closeAll(Socket socket, InputStream inputStream, OutputStream outputStream, Scanner scanner) {
		if (scanner != null) {
			scanner.close();
		}
		if (outputStream != null) {
			try {
				outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (inputStream != null) {

				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}

				if (socket != null) {
					try {
						socket.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	public static void main(String[] args) {

		String host = "192.168.1.89";
		int port = 8888;
		System.out.println();
		new ChatClient().chat(host, port);
	}
}
